/**
 * 购物车模块
 */
define(function(require, exports, module) {
	"require:nomunge,exports:nomunge,module:nomunge";

	require("../../custom/base/component-core.js");
	
	var base = require("../../custom/base/component-base.js");
	
	base.init(base);
	
	var async = require("../../custom/base/component-async.js");
	
	var validate= require("../../custom/base/component-validate.js");
		
	//初始化函数
	exports.init=function(m){
				
		window.$ldh_cart=m;
		
		exports.getCartList();
	};
	
	//设置商家代码
	exports.setShopId=function(shopId){
		
		this.shopId=shopId;
		
	};
	
	//获取商家代码
	exports.getShopId=function(){
		
		return this.shopId;
		
	};
	
	
	
	//查询购物车数量
	exports.getCartNum=function(){
			var params = {
					shopId:exports.getShopId()
			};
			eval(
					Wind.compile("async", function() {

						var data = $await(async.DDF_AsyncRequest("POST",ctx+"/shopweb/Cart/getCartShopNum.do", params));

								if(data["code"]==1){
									$("#cartNum").html(data["nums"]);
									$("#price").html(data["prices"].toFixed(2));
								}else{
									$("#cartNum").html("0.00");
								}
								
			}))().start();
	};
	
    
	//添加商品到购物车
	
	exports.addCartNum=function(shopId,merchandiseId){
		
		var params = {
				shopId:shopId,
				merchandiseId:merchandiseId
			};
		
		eval(
				Wind.compile("async", function() {

					var data = $await(async.DDF_AsyncRequest("POST",ctx+"/shopweb/Cart/addshoptoCart.do", params));

							if(data["code"]==1){
								
							}else{
								
								alert(data["message"]);
							}
							
							
							
		}))().start();
		
	};
	
	//定时提示信息
	var tips_task = eval(Wind.compile("async", function (divId) {
		
	    $await(Wind.Async.sleep(2000));
	   
	    $(divId).hide();
	    
	    
	}));
	
	var task = eval(Wind.compile("async", function (divId) {
	    $await(tips_task(divId));
	}));
	//从购物车删除商品
	
	exports.deleteCartNum=function(merchandiseId,cartId){
		
		
			var params = {
				cartId:cartId,
				nums:nums
			};
			
			
		eval(
				Wind.compile("async", function() {

					var data = $await(async.DDF_AsyncRequest("POST",ctx+"/shopweb/Cart/updateCartShopsNum.do", params));

							if(data["code"]==1){
								
								
							}else{
								
								
							}
							
							
							
		}))().start();
		
	};
	
	
	//更新购物车数量
	var clickable=true;
	exports.updateCartNum=function(cartId,price,opt){
		
		if(!clickable){
			return;
		}
		
		clickable=false;
		
		var nums=Number($("#"+cartId+" span").text());
		
		if(opt=="add"){
			//$("#"+cartId+" .button_add").attr("disabled","disabled");
			nums=nums+1;
			
		}else{
			//$("#"+cartId+" .button_sub").attr("disabled","disabled");
			nums=nums-1;
		}
		
		
		base.showLoading();
		
		
		
		if(nums==0){
			
			exports.deleteCartItem(cartId,price);
			
		}else{
			
			var params = {
					cartId:cartId,
					nums:nums,
					userId:$ldh_base.getCookie("userId"),
					loginSign:$ldh_base.getCookie("loginSign"),
					sign:MD5($ldh_base.getCookie("loginSign")+cartId+nums)
				};
				eval(
						Wind.compile("async", function() {

							var data = $await(async.DDF_AsyncRequest("POST",ctx+"/shopapp/Cart/updateCartShopsNum.do", params));

									if(data["code"]==1){
										
										
										$("#"+cartId+" span").html(nums);
										
										if(opt=="add"){
											
											$("#row"+cartId).parent().find(".cart_statistics b:eq(0)").html(Number($("#row"+cartId).parent().find(".cart_statistics b:eq(0)").text())+1);

											$("#row"+cartId).parent().find(".cart_statistics em").html((Number($("#row"+cartId).parent().find(".cart_statistics em").text())+Number(price)).toFixed(2));

											$("#ldhCart .cart_btm em:eq(0)").html(Number($("#ldhCart .cart_btm em:eq(0)").text())+1);
											
										    $("#ldhCart .cart_btm em:eq(1)").html((Number($("#ldhCart .cart_btm em:eq(1)").text())+Number(price)).toFixed(2));
										    
										   // $("#"+cartId+" .button_add").attr("disabled",false);
										}else{
											
											$("#row"+cartId).parent().find(".cart_statistics b:eq(0)").html(Number($("#row"+cartId).parent().find(".cart_statistics b:eq(0)").text())-1);

											$("#row"+cartId).parent().find(".cart_statistics em").html((Number($("#row"+cartId).parent().find(".cart_statistics em").text())-price).toFixed(2));

											$("#ldhCart .cart_btm em:eq(0)").html(Number($("#ldhCart .cart_btm em:eq(0)").text())-1);
											
										    $("#ldhCart .cart_btm em:eq(1)").html((Number($("#ldhCart .cart_btm em:eq(1)").text())-Number(price)).toFixed(2));
										    
										  //  $("#"+cartId+" .button_sub").attr("disabled",false);
										}
										
										
										
										
									}else{
										
										showTips(data["message"]);
									}
									
									clickable=true;
									
									base.cancelLoading();
									
				}))().start();
			
		}
		
		
		
	};
	
	//删除购物车商品
	exports.deleteCartItem=function(cartId,price){
		
		var params = {
			cartId:cartId
		};
		eval(
				Wind.compile("async", function() {

					var data = $await(async.DDF_AsyncRequest("POST",ctx+"/shopweb/Cart/deleteCartShop.do", params));

							if(data["code"]==1){
								
								
								$("#row"+cartId).parent().find(".cart_statistics b:eq(0)").html(Number($("#row"+cartId).parent().find(".cart_statistics b:eq(0)").text())-1);

								$("#row"+cartId).parent().find(".cart_statistics em").html((Number($("#row"+cartId).parent().find(".cart_statistics em").text())-price).toFixed(2));

								$("#ldhCart .cart_btm em:eq(0)").html(Number($("#ldhCart .cart_btm em:eq(0)").text())-1);
								
							    $("#ldhCart .cart_btm em:eq(1)").html((Number($("#ldhCart .cart_btm em:eq(1)").text())-Number(price)).toFixed(2));
							    
							    
							    var parent=$("#row"+cartId).parent();
							    
								$("#row"+cartId).remove();

								if(parent.find(".clearfix").length==0){
									
									parent.remove();
								}
							    
								
								if($("#ldhCart .cart .box_block ul").length==0){
									
									cartNull("#ldhCart .cart");
									
								}
							}else{
								
							}
							
							clickable=true;
					base.cancelLoading();
							
		}))().start();
		
	};
	
	//购物车列表
	exports.getCartList=function(shopId){

		var params = {
				userId:$ldh_base.getCookie("userId"),
				loginSign:$ldh_base.getCookie("loginSign"),
				sign:MD5($ldh_base.getCookie("loginSign")+$ldh_base.getCookie("userId"))
			};
		
		base.showLoading();
		
			eval(
					Wind.compile("async", function() {

						var data = $await(async.DDF_AsyncRequest("POST",ctx+"/shopapp/Cart/getCartShops.do", params));
								if(data["code"]==1){
								
									var htmlStr="",totalPrice=0,totalNums=0;
									
									for(var i=0;i<data["data"].length;i++){
										
											var logoUrl=data["data"][i]["logoUrl"];
											
											if(logoUrl=="" || logoUrl.indexOf(".")<0){
												
												logoUrl= ctx+'/v1/img/category_f.png';
											}else{
												
												logoUrl=fileOpenUrl+logoUrl;
											}
											
										
										
											var merHtml="";singlePrice=0,nums=0;
											
											for(var j=0;j<data["data"][i]["goods"].length;j++){
												
												var picdefault=data["data"][i]["goods"][j]["picdefault"];
												
												if(validate.isNull(picdefault)){
													
													picdefault=ctx+"/v1/img/default_234_220.png";
												}else{
													
													picdefault=fileOpenUrl+picdefault;
												}
												
												singlePrice+=Number(data["data"][i]["goods"][j]["price"])*parseInt(data["data"][i]["goods"][j]["nums"]);
												nums+=data["data"][i]["goods"][j]["nums"];

												merHtml += '<li class="clearfix" id="row'+data["data"][i]["goods"][j]["cartId"]+'">';
												merHtml += '<table>';
												merHtml += '<colgroup><col width="34px"/></colgroup>';
												merHtml += '<tr>';
												merHtml += '<td>';
												merHtml += '<span class="checkbox checked" onclick="$ldh_cart.selectItem(this)">';
												merHtml += '<input data-role="none" name="cartIds" type="checkbox" class="opacity_0" value="'+data["data"][i]["goods"][j]["cartId"]+'" checked="checked"/>';
												merHtml += '</span>';
												merHtml += '</td>';
												merHtml += '<td>';
												merHtml += '<div class="cart_goods">';
												merHtml += '<div class="store_goods_pic"><a data-transition="none" href="#"><img src="'
														+ picdefault
														+ '"/></a></div>';
												merHtml += '<div class="store_goods_info">';
												merHtml += '<h3>'
														+ base.subString(data["data"][i]["goods"][j]["merchandiseName"],10)
														+ '</h3>';
												merHtml += '<p class="cart_price">¥<em>'
														+ data["data"][i]["goods"][j]["price"]
														+ '</em></p>';
												merHtml += '</div>';
												merHtml += '<div class="store_goods_addsub" id="'+data["data"][i]["goods"][j]["cartId"]+'">';
												merHtml += '<button data-role="none" type="button" class="button_sub" onclick=$ldh_cart.updateCartNum("'+data["data"][i]["goods"][j]["cartId"]+'","'+data["data"][i]["goods"][j]["price"]+'","sub")>-</button>';
												//merHtml += '<span class="icon_x" style="display:none">x</span>';
												merHtml += '<span>'+data["data"][i]["goods"][j]["nums"]+'</span>';
												merHtml += '<button  data-role="none" type="button" class="button_add" onclick=$ldh_cart.updateCartNum("'+data["data"][i]["goods"][j]["cartId"]+'","'+data["data"][i]["goods"][j]["price"]+'","add")>+</button>';
												merHtml += '</div>';
												merHtml += '</div>';
												merHtml += '</td>';
												merHtml += '</tr>';
												merHtml += '</table> ';
												merHtml += '</li>';
												
												
											}
											
											totalPrice+=singlePrice;
											totalNums+=nums;
											
										/*	htmlStr += '<dl id="cartItem'+i+'">';
											htmlStr += '<dt style="background-color:#f5f4f2;">';
											htmlStr += '<table>';
											htmlStr += '<colgroup>';
											htmlStr += '<col width="44px" />';
											htmlStr += '<col width="34px" />';
											htmlStr += '<col width="164px" />';
											htmlStr += '<col width="63px" />';
											htmlStr += '</colgroup>';
											htmlStr += '<tbody>';
											htmlStr += '<tr>';
											htmlStr += '<td><span class="ldh-checkbox-span checked" onclick=$ldh_cart.selectAllItem('+i+')><input type="checkbox" class="opacity_0" /></span></td>';
											htmlStr += '<td><span class="ldh-shop-logo"><a href=javascript:$ldh_base.jumpToShopIndex("'+data["data"][i]["shopId"]+'")><img src="'+logoUrl+'" /></a></span></td>';
											htmlStr += '<td><span class="ldh-shop-name"><a href=javascript:$ldh_base.jumpToShopIndex("'+data["data"][i]["shopId"]+'")>'+data["data"][i]["shopName"]+'</a></span><span class="ldh-goods-num"></span></td>';
											//htmlStr += '<td class="text-center"><span class="ldh-cart-tips" id="tip_amount"></span></td>';
											htmlStr += '<td class="text-right"><button type="button" class="ldh-closing-btn ldh-bg-yellow">¥<b id="singlePrice'+i+'">'+singlePrice.toFixed(2)+'</b><b style="display:none;">'+data["data"][i]["minAmount"]+'</b></button></td>';
											htmlStr += '</tr>';
											htmlStr += '</tbody>';
											htmlStr += '</table>';
											htmlStr += '</dt>';
											htmlStr +=merHtml;
											htmlStr += '<dd class="ldh-recess-tips" id="tip_businesss" style="display:none;">';
											//htmlStr += '<span>温馨提示:店铺休息中,暂停服务.</span><span class="allowAddOrder" style="display:none;">'+data["data"][i]["allowAddOrder"]+'</span>';
											htmlStr += '<span>'+data["data"][i]["allowAddOrder"]+'</span>';
											htmlStr += '</dd>';
											htmlStr += '</dl>';*/
											

											htmlStr += '<div class="box_block">';
											htmlStr += '<ul id="cartItem'+i+'">';
											htmlStr += '<li>';
											htmlStr += '<table>';
											htmlStr += '<colgroup><col width="34px"/></colgroup>';
											htmlStr += '<tr>';
											htmlStr += '<td>';
											htmlStr += '<span class="checkbox checked" onclick="$ldh_cart.selectAllItem('+i+')">';
											htmlStr += '<input data-role="none" type="checkbox" class="opacity_0" />';
											htmlStr += '</span>';
											htmlStr += '</td>';
											htmlStr += '<td>';
											htmlStr += '<span class="cart_title">'+data["data"][i]["shopName"]+'</span>';
											htmlStr += '<span class="cart_tips"></span>';
											/*if(!validate.isNull(data["data"][i]["minAmount"])){
												var minAmount=Number(data["data"][i]["minAmount"]-Number(singlePrice));
												if(minAmount>0){
													htmlStr += '<span class="cart_tips">还差'+minAmount+'元起送</span>';
												}
											}*/
											htmlStr += '</td>';
											htmlStr += '</tr>';
											htmlStr += '</table>';
											htmlStr += '</li>';
											htmlStr += '<input type="hidden" name="allowAddOrder" value="'+data["data"][i]["allowAddOrder"]+'">';
											htmlStr += '<input type="hidden" name="minAmount" value="'+data["data"][i]["minAmount"]+'">';
											htmlStr += '<li class="text-right cart_statistics"><span>共<b>'+nums+'</b>件商品</span> <span>合计：<b>¥<em>'+singlePrice.toFixed(2)+'</em></b></span></li>';
											htmlStr +=merHtml;
											htmlStr += '</ul>';
											htmlStr += '</div>';
											
											
										
									}
								
									$("#ldhCart .cart").html(htmlStr);
									
									

							        $("#ldhCart .cart_btm em:eq(0)").html(totalNums);
							        $("#ldhCart .cart_btm em:eq(1)").html(totalPrice.toFixed(2));
							
									//$("#totalPrice").html(totalPrice.toFixed(2));
									
							        if(data["data"].length==0){
										cartNull("#ldhCart .cart");
									}else{
										re_cartNull("#ldhCart .cart");
									}
									
								
								}else if(data["code"]=="-4444"){
									
									window.location.href=ctx+"/h5/login.shtml?fromPage=ldhCart";
									
								}
								base.cancelLoading();
								
							
								
			}))().start();

	};

	// 选择商家的全部商品
	exports.selectAllItem=function(position){
		
		
		if($("#cartItem"+position+" span:eq(0)").hasClass("checked")){
			
			
			$("#cartItem"+position+" span").removeClass("checked");
			
			$("#cartItem"+position+" span").children().attr("checked",false);
			
			 $("#ldhCart .cart_btm em:eq(0)").html(Number($("#ldhCart .cart_btm em:eq(0)").text())-Number($("#cartItem"+position+" .cart_statistics b:eq(0)").text()));

			 $("#ldhCart .cart_btm em:eq(1)").html((Number($("#ldhCart .cart_btm em:eq(1)").text())-Number($("#cartItem"+position+" .cart_statistics em").text())).toFixed(2));
		

		}else{
			 $("#ldhCart .cart_btm em:eq(0)").html(Number($("#ldhCart .cart_btm em:eq(0)").text())+Number($("#cartItem"+position+" .cart_statistics b:eq(0)").text()));

			 $("#ldhCart .cart_btm em:eq(1)").html((Number($("#ldhCart .cart_btm em:eq(1)").text())+Number($("#cartItem"+position+" .cart_statistics em").text())).toFixed(2));

			$("#cartItem"+position+" span").addClass("checked");
			
			$("#cartItem"+position+" span").children().attr("checked",true);

		}
		
		
		
	};
	
	//选择某个商品
	exports.selectItem=function(obj){
		
		var row=$(obj).parent().parent().parent().parent().parent();
		
		var price=Number($(obj).parent().parent().find(".store_goods_info em").text());
		
		var num=Number($(obj).parent().parent().find(".store_goods_addsub span").text());

		if($(obj).hasClass("checked")){
			
			$(obj).removeClass("checked");
			
			$(obj).children().attr("checked",false);
			
			row.parent().find(".cart_statistics b:eq(0)").html(Number(row.parent().find(".cart_statistics b:eq(0)").text())-num);

			row.parent().find(".cart_statistics em").html((Number(row.parent().find(".cart_statistics em").text())-Number(price*num)).toFixed(2));
			
			 $("#ldhCart .cart_btm em:eq(0)").html(Number($("#ldhCart .cart_btm em:eq(0)").text())-num);

			 $("#ldhCart .cart_btm em:eq(1)").html((Number($("#ldhCart .cart_btm em:eq(1)").text())-(price*num)).toFixed(2));
		
		}else{
			
			row.parent().find(".checkbox:eq(0)").addClass("checked");
			
			$(obj).addClass("checked");
			
			$(obj).children().attr("checked",true);
			
			row.parent().find(".cart_statistics b:eq(0)").html(Number(row.parent().find(".cart_statistics b:eq(0)").text())+num);

			row.parent().find(".cart_statistics em").html((Number(row.parent().find(".cart_statistics em").text())+Number(price*num)).toFixed(2));
			
			 $("#ldhCart .cart_btm em:eq(0)").html(Number($("#ldhCart .cart_btm em:eq(0)").text())+num);

			 $("#ldhCart .cart_btm em:eq(1)").html((Number($("#ldhCart .cart_btm em:eq(1)").text())+(price*num)).toFixed(2));
		}
		
		var flag=true;
		
		for(var i=1;i<row.parent().find(".checkbox").length;i++){
			
			if(row.parent().find(".checkbox:eq("+i+")").hasClass("checked")){
				//表示购物车中的某个商家还有商品是选中的 
				flag=false;
			}
			
		}
		//如果全部商品都没有选中,那就把商家左边的勾去掉
		if(flag){
			row.parent().find(".checkbox:eq(0)").removeClass("checked");
			row.parent().find(".checkbox:eq(0)").children().attr("checked",false);
		}
			
	};
	
	//结算
	
	var curShopName="";
	
	exports.settle=function(){
	
		
		if(!isMerNull()){
			
			showTips("请选择商品");
			return;
			
		}
		
		if(!isBusinessStatus()){
			
			showTips("'"+curShopName+"'休息中,暂停服务");
			
			return;
		}
		
		

		isMinAmount(true);
		
		
	};
	
	
	
	//判断是否选择了商品
	function isMerNull(){
		
		var flag=false;
		
		for(var i=0;i<$("#ldhCart .cart .box_block").length;i++){
			
			if($("#cartItem"+i+" li:eq(0) .checkbox").hasClass("checked")){
				
				flag=true;
			}
			
		}
		
		return flag;
	}
	
	
	//判断商家营业状态
	function isBusinessStatus(){
		
		//判断购物车中的店铺列表是否存在某一间是休息中,如有有的，则不能购买
		var businessStatusFlag=true;
		for(var i=0;i<$("#ldhCart .cart .box_block").length;i++){
			
			if($("#cartItem"+i+" li:eq(0) .checkbox").hasClass("checked") && $("#cartItem"+i+" input[name='allowAddOrder']").val()!=1){
				
					businessStatusFlag=false;
					
					curShopName=$("#cartItem"+i+" .cart_title").text();
					
					break;
				
			}
		}
		return businessStatusFlag;
		
	}
	
	//判断起送金额是否足够
	function isMinAmount(flag){
		
		//判断起送金额是否足够
		var minAmountFlag=true,minAmount=0,curAmount=0;
		
		for(var i=0;i<$("#ldhCart .cart .box_block").length;i++){
			
			if($("#cartItem"+i+" li:eq(0) .checkbox").hasClass("checked")){
				
				if(Number($("#cartItem"+i+" .cart_statistics em").text())<Number($("#cartItem"+i+" input[name='minAmount']").val())){
					
					minAmountFlag=false;
					
					curAmount=$("#cartItem"+i+" .cart_statistics em").text();
					
					minAmount=$("#cartItem"+i+" input[name='minAmount']").val();
					
					curShopName=$("#cartItem"+i+" .cart_title").text();
					
					break;
				}
				
			}
			
		}
		
		
		if(minAmountFlag){
			
				if(!flag)
					return;
			
				var cartId="";
				
				var arr_cart_id = new Array();
				
				$("#ldhCart .cart input[name='cartIds'][type='checkbox']").each(function(){
					if($(this).is(":checked")){
						arr_cart_id.push($(this).val());
					}
				});
				
				cartId= arr_cart_id.join(",");
				
				//跳转到结算页面
				//window.location.href="?cartIds="+cartId+"#ldhOrder";
				
				window.location.href=ctx+"/h5/suborder/"+cartId+".shtml";
				
		}else{
			showTips("'"+curShopName+"'还差"+(Number(minAmount)-Number(curAmount)).toFixed(2)+"元起送");
		}
		
	}
	
	//购物车为空
	function cartNull(divId){
			var cartnull='<div class="cart_null">亲，购物车暂无商品，赶紧购物吧！</div>';
			$(divId).append(cartnull);
	}
	
	//购物车不为空
	function re_cartNull(divId){
			$(divId).find(".cart_null").remove();
	}
	
});